﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;
using ChinaCustoms.Qingdao.Workflow.Permissions;
using System.Collections.ObjectModel;
using ChinaCustoms.Qingdao.Workflow.Supports;
using ChinaCustoms.Framework.DeluxeWorks.Library.OGUPermission;
using ChinaCustoms.Qingdao.Workflow.Controls;

public partial class Utility_UserSelector : System.Web.UI.Page
{
    private IList<TreeNode> selectedNodes;
    /// <summary>
    /// 被选中的节点
    /// </summary>
    public IList<TreeNode> SelectedNodes
    {
        get { return selectedNodes; }
        set { selectedNodes = value; }
    }

    private int nodeCount = 0;

    string ApplicationCodeName = string.Empty;
    string OrganizationIDs = string.Empty;
    string RoleNames = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.ApplicationCodeName = ConfigurationManager.AppSettings["ApplicationCodeName"];

        if (this.Request.QueryString["OrganizationIDs"] != null)
            this.OrganizationIDs = this.Request.QueryString["OrganizationIDs"];

        if (this.Request.QueryString["RoleNames"] != null)
            this.RoleNames = this.Request.QueryString["RoleNames"];

        if (this.IsPostBack == false)
        {
            this.BuildeTree();
        }
    }

    protected void SelectButton_Click(object sender, EventArgs e)
    {
        this.selectedNodes = new List<TreeNode>();
        string selectedNameArray = string.Empty;
        string selectedIDArray = string.Empty;
        this.GetSelectedNodes(this.TreeView1.Nodes[0],this.TreeView1.Nodes[0].Checked);
        for (int i = 0; i < selectedNodes.Count; i++)
        {
            selectedIDArray += string.Format("{0},", selectedNodes[i].Value);
            selectedNameArray += string.Format("{0},", selectedNodes[i].Text);
        }
        if (selectedIDArray.EndsWith(","))
        {
            selectedIDArray = selectedIDArray.Substring(0, selectedIDArray.Length - 1);
        }

        if (selectedNameArray.EndsWith(","))
        {
            selectedNameArray = selectedNameArray.Substring(0, selectedNameArray.Length - 1);
        }

        string returnValue = string.Format("\"{0}|{1}\"", selectedNameArray, selectedIDArray);
        ModalUtil.ClosePage(Page, returnValue);
    }

    protected void CancelButton_Click(object sender, EventArgs e)
    {
        ModalUtil.ClosePage(Page);
    }

    private void GetSelectedNodes(TreeNode currentNode,bool parentNodeState)
    {
        if (currentNode.ToolTip == "user")
        {
            if (currentNode.Checked == true || parentNodeState == true)
            {
                selectedNodes.Add(currentNode);
            }
        }

        if (currentNode.ChildNodes.Count > 0)
        {
            foreach (TreeNode tempnode in currentNode.ChildNodes)
            {
                bool tempState = false;
                if (currentNode.Checked == true || parentNodeState == true)
                {
                    tempState = true;
                }
                GetSelectedNodes(tempnode, tempState);
            }
        }
    }

    private void BuildeTree()
    {
        this.TreeView1.ShowLines = true;
        this.TreeView1.ExpandDepth = 2;
        this.TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
        this.TreeView1.Nodes.Clear();

        List<IUser> usersForSelect = ChinaCustomsPermissionWrapper.GetUsers(this.ApplicationCodeName, this.RoleNames.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries), this.OrganizationIDs.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries),false);

        Dictionary<string, List<IUser>> usersForSelectDictionary = new Dictionary<string, List<IUser>>();

        List<string> organizationsOfUsers = new List<string>();
        foreach (IUser user in usersForSelect)
        {
            IOrganization _organization = user.Parent;

            if (usersForSelectDictionary.ContainsKey(_organization.ID))
            {
                usersForSelectDictionary[_organization.ID].Add(user);
            }
            else
            {
                List<IUser> users = new List<IUser>();
                users.Add(user);
                usersForSelectDictionary.Add(_organization.ID, users);
            }

            while (_organization != null)
            {
                if (!organizationsOfUsers.Contains(_organization.ID))
                {
                    organizationsOfUsers.Add(_organization.ID);
                }

                _organization = _organization.Parent;
                //_organization = this.PermissionClient.GetOrganization(_organization.ParentID);
            }
        }

        IOrganization rootOrg = ChinaCustomsPermissionWrapper.GetRootOrganization();

        TreeNode rootNode = new TreeNode();
        rootNode.Value = rootOrg.ID;
        rootNode.Text = rootOrg.Name;
        rootNode.SelectAction = TreeNodeSelectAction.Expand;
        this.TreeView1.Nodes.Add(rootNode);

        PopulateTreeNodes(rootNode, rootOrg, usersForSelectDictionary, organizationsOfUsers);
        if (nodeCount == 0)
        {
            this.LitDisplay.Text = "没有符合选定条件的用户.";
            this.LitDisplay.Visible = true;
            this.TreeView1.Visible = false;
        }
    }



    void PopulateTreeNodes(TreeNode parentNode, IOrganization parentOrganization, Dictionary<string, List<IUser>> usersForSelectDictionary, List<string> organizationsOfUsers)
    {
        if (parentOrganization!=null && usersForSelectDictionary.ContainsKey(parentOrganization.ID))
        {
            for (int i = usersForSelectDictionary[parentOrganization.ID].Count - 1; i >= 0; i--)
            {
                IUser _user= usersForSelectDictionary[parentOrganization.ID][i];
                TreeNode userNode = new TreeNode();
                userNode.Text = _user.DisplayName;
                userNode.Value = _user.LogOnName;
                userNode.SelectAction = TreeNodeSelectAction.None;
                userNode.ToolTip = "user";
                nodeCount++;
                parentNode.ChildNodes.Add(userNode);

                usersForSelectDictionary[parentOrganization.ID].RemoveAt(i);
            }
        }

        OguObjectCollection<IOguObject> childOrgs = parentOrganization.Children;
        foreach (IOguObject _orgObject in childOrgs)
        {
            IOrganization _organization = _orgObject as IOrganization;
            if (_organization != null)
            {
                if (organizationsOfUsers.Contains(_organization.ID))
                {
                    TreeNode organizationNode = new TreeNode();
                    organizationNode.Value = _organization.ID;
                    organizationNode.Text = _organization.DisplayName;
                    organizationNode.SelectAction = TreeNodeSelectAction.Expand;
                    organizationNode.ToolTip = "org";
                    nodeCount++;
                    parentNode.ChildNodes.Add(organizationNode);

                    if (usersForSelectDictionary.ContainsKey(_organization.ID))
                    {
                        for (int i = usersForSelectDictionary[_organization.ID].Count - 1; i >= 0;i-- )
                        {
                            IUser _user = usersForSelectDictionary[_organization.ID][i];
                            TreeNode userNode = new TreeNode();
                            userNode.Text = _user.DisplayName;
                            userNode.Value = _user.LogOnName;
                            userNode.SelectAction = TreeNodeSelectAction.None;
                            userNode.ToolTip = "user";
                            nodeCount++;
                            organizationNode.ChildNodes.Add(userNode);
                            usersForSelectDictionary[_organization.ID].RemoveAt(i);
                        }
                    }

                    PopulateTreeNodes(organizationNode, _organization, usersForSelectDictionary, organizationsOfUsers);
                }
            }
        }
    }

    protected void btnSearchBlurUser_Click(object sender, EventArgs e)
    {
        //this.PermissionClient.GetUser();
    }


    //protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
    //{
    //    TreeNode node= e.Node;
    //    if (node != null)
    //    {
    //        SetChildrenNodeState(node,node.Checked);
    //    }
    //}

    //private void SetChildrenNodeState(TreeNode parentNode, bool nodeState)
    //{
    //    parentNode.Checked = nodeState;

    //    if (parentNode.ChildNodes != null && parentNode.ChildNodes.Count > 0)
    //    {
    //        for (int i = 0; i < parentNode.ChildNodes.Count; i++)
    //        {
    //            SetChildrenNodeState(parentNode.ChildNodes[i], nodeState);
    //        }
    //    }
    //}
}
